﻿using System;
using System.Text;
using System.Security.Cryptography;

namespace FIS.iDET.Keygen
{

    /// <summary>
    /// Calculate a serial number that matches a unique machine ID of a computer
    /// </summary>

  // Hoang add code ...
    public class LicenseService
    {
        public static string GenarateSerialNumberFrom(string machineID)
        {
            string serial = GetHash(
                "ID >> " + machineID +
                "Secret >> " + "aed45dba1f73080de226c193d3f9d605"
            );
            return serial;
        }

        /// <summary>
        /// generate 16-byte hash of a string
        /// </summary>
        /// <param name="s">input string</param>
        /// <returns>16-byte hash string</returns>
        private static string GetHash(string s)
        {
            MD5 sec = new MD5CryptoServiceProvider();
            ASCIIEncoding enc = new ASCIIEncoding();
            byte[] bt = enc.GetBytes(s);
            return GetHexString(sec.ComputeHash(bt));
        }
        
        /// <summary>
        /// intended to be used by GetHash()
        /// </summary>
        /// <param name="bt">input string</param>
        /// <returns>hex string</returns>
        private static string GetHexString(byte[] bt)
        {
            string s = string.Empty;
            for (int i = 0; i < bt.Length; i++)
            {
                byte b = bt[i];
                int n, n1, n2;
                n = (int)b;
                n1 = n & 15;
                n2 = (n >> 4) & 15;
                if (n2 > 9)
                    s += ((char)(n2 - 10 + (int)'A')).ToString();
                else
                    s += n2.ToString();
                if (n1 > 9)
                    s += ((char)(n1 - 10 + (int)'A')).ToString();
                else
                    s += n1.ToString();
                if ((i + 1) != bt.Length && (i + 1) % 2 == 0) s += "-";
            }
            return s;
        }
    }
}
